import 'dart:async';
import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hive/hive.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:record/record.dart';
import 'package:ichinesereader/utils/play_button_notifier.dart';
import '../../constants.dart';
import '../../controller/recorder.dart';
import '../../controller/cache.dart';
import '../../service/recorder.dart';
import '../../utils/progress_notifier.dart';
import 'package:ichinesereader/controller/audiobooks.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/pages/book/bookForApp.dart';

AudioBooksController _audiobooksManager = Get.find();
//RecorderController _recorderController = Get.put(RecorderController());
RecorderController _recorderController = Get.find();
RecorderServiceProvider _recorderServiceProvider =
    new RecorderServiceProvider();
final _audioRecorder = Record();
String _path = '';
String? _assignmentId = '';
String _bookId = '';

class MyRecorder extends StatelessWidget {
  const MyRecorder({Key? key, this.bookId, this.assignmentId})
      : super(key: key);
  final String? bookId;
  final String? assignmentId;

  @override
  Widget build(BuildContext context) {
    // used by save and share
    _bookId = bookId!;
    _assignmentId = assignmentId;
    bool isStudent = true;
    bool isIndividual = false;
    final box = Hive.box('appconfig');
    isStudent = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Student;
    isIndividual = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Individual;
    return Container(
        height: 160,
        width: 280,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Row(
              children: [
                Obx(
                  () => _buildRecordStopControl(
                      _recorderController.isRecording.value,
                      _recorderController.isPaused.value),
                ),
                isStudent || isIndividual
                    ? Obx(() {
                        if (_recorderController.showSave.value == true) {
                          return _buildSaveControl();
                        } else {
                          return Text('');
                        }
                      })
                    : Text(''),
                isStudent || isIndividual
                    ? Obx(() {
                        if (_recorderController.showSave.value == true) {
                          return _buildShareControl();
                        } else {
                          return Text('');
                        }
                      })
                    : Text(''),
                Obx(() {
                  return _buildPauseResumeControl(
                      _recorderController.isRecording.value,
                      _recorderController.isPaused.value);
                }),
                Obx(() {
                  if (_recorderController.isRecording.value == true ||
                      _recorderController.isPaused.value == true) {
                    return _buildTimerText(
                        _recorderController.recordDuration.value.toInt());
                  } else {
                    return Text('');
                  }
                }),
              ],
            ),
            const SizedBox(height: 10),
            // current method
            Obx(() {
              if (_recorderController.showPlayer.value == true) {
                if (_recorderController.bookRecordingLocation.value != '') {
                  _audiobooksManager.setRecord(
                      _recorderController.bookRecordingLocation.value);
                }
                return Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Color.fromARGB(209, 167, 169, 170),
                      borderRadius: BorderRadius.only(
                        topRight: Radius.circular(10.0),
                        topLeft: Radius.circular(10.0),
                        bottomLeft: Radius.circular(10.0),
                        bottomRight: Radius.circular(10.0),
                      ),
                    ),
                    child: Row(
                      children: [
                        PlayButton(),
                        const SizedBox(width: 10),
                        Container(
                            width: 200,
                            margin: const EdgeInsets.only(top: 17.0),
                            child: AudioProgressBar()),
                      ],
                    ));
              } else {
                return Text('');
              }
            }),
          ],
        ));
  }
}

Widget _buildRecordStopControl(_isRecording, _isPaused) {
  late Icon icon;
  late Color color;
  if (_isRecording == true || _isPaused == true) {
    icon = const Icon(Icons.stop, color: Colors.red, size: 30);
    color = Colors.red.withOpacity(0.1);
  } else {
    icon = Icon(Icons.mic, color: Color.fromARGB(255, 98, 191, 240), size: 30);
    color = Color.fromARGB(255, 98, 191, 240).withOpacity(0.1);
  }

  return ClipOval(
    child: Material(
      color: color,
      child: InkWell(
        child: SizedBox(width: 56, height: 56, child: icon),
        onTap: () {
          _isRecording == true ? _stop() : _start();
        },
      ),
    ),
  );
}

Widget _buildSaveControl() {
  late Icon icon;
  late Color color;

  icon = Icon(Icons.save_outlined,
      color: Color.fromARGB(255, 98, 191, 240), size: 30);
  color = Color.fromARGB(255, 98, 191, 240).withOpacity(0.1);

  return ClipOval(
    child: Material(
        color: color,
        child: InkWell(
          child: SizedBox(width: 56, height: 56, child: icon),
          onTap: () {
            _save();
          },
        )),
  );
}

Widget _buildShareControl() {
  late Icon icon;
  late Color color;
  icon = Icon(Icons.share_outlined,
      color: Color.fromARGB(255, 98, 191, 240), size: 30);
  color = Color.fromARGB(255, 98, 191, 240).withOpacity(0.1);

  return ClipOval(
    child: Material(
      color: color,
      child: InkWell(
        child: SizedBox(width: 56, height: 56, child: icon),
        onTap: () {
          _share();
        },
      ),
    ),
  );
}

Widget _buildPauseResumeControl(_isRecording, _isPaused) {
  if (_isRecording == false && _isPaused == false) {
    return const SizedBox.shrink();
  }
  late Icon icon;
  late Color color;

  if (_isPaused == false) {
    icon = const Icon(Icons.pause, color: Colors.red, size: 30);
    color = Colors.red.withOpacity(0.1);
  } else {
    icon = const Icon(Icons.play_arrow, color: Colors.red, size: 30);
    color = Color.fromARGB(255, 98, 191, 240).withOpacity(0.1);
  }

  return ClipOval(
    child: Material(
      color: color,
      child: InkWell(
        child: SizedBox(width: 56, height: 56, child: icon),
        onTap: () {
          _isPaused == true ? _resume() : _pause();
        },
      ),
    ),
  );
}

Future<void> _start() async {
  try {
    if (await _audioRecorder.hasPermission()) {
      // We don't do anything with this but printing
      final isSupported = await _audioRecorder.isEncoderSupported(
        AudioEncoder.aacLc,
      );
      if (kDebugMode) {
        Log.debug(
            '${AudioEncoder.aacLc.name} ----------******------supported -:)): $isSupported');
      }
      globalController.evaluateJavascript(source: "pauseRead()");
      await _audioRecorder.start(
          //path: 'aFullPath/myFile.m4a',
          //encoder: AudioEncoder.aacLc, // by default
          //bitRate: 128000, // by default
          //samplingRate: 16000, // notwork
          );

      await _audioRecorder.isRecording();
      _recorderController.startRecordState();
      _recorderController.setRecordTime();
    }
  } catch (e) {
    if (kDebugMode) {
      print(e);
    }
  }
}

Future<void> _stop() async {
  final path = await _audioRecorder.stop();
  _path = path!;
  _audiobooksManager.setRecord(path);
  _recorderController.stopRecordState(path);
  globalController.evaluateJavascript(source: "resumeRead()");
}

Future<void> _pause() async {
  await _audioRecorder.pause();
  _recorderController.pauseRecordState();
  //globalController.evaluateJavascript(source: "resumeRead()");
}

Future<void> _resume() async {
  // put _recorderController.setRecordTime at first line
  _recorderController.setRecordTime();
  await _audioRecorder.resume();
  _recorderController.resumeRecordState();
}

Future<void> _save() async {
  //Int8List fileContent = await File(path).readAsBytes();
  EasyLoading.show();
  try {
    await _recorderServiceProvider.saveRecordFileInBook(
        _path, _bookId, _assignmentId);
    if (_recorderServiceProvider.statusMessageResult.value.status == 1000) {
      showSnackMsg('Saved Successfully');
      // Get.snackbar('Message'.tr, 'Saved Successfully'.tr,
      //     backgroundColor: Get.theme.primaryColor,
      //     colorText: Get.theme.primaryColorLight,
      //     snackPosition: SnackPosition.BOTTOM);
    } else {
      showSnackMsg('Error to save');
      // Get.snackbar('Message'.tr, 'Error to save'.tr,
      //     backgroundColor: Get.theme.primaryColor,
      //     colorText: Get.theme.primaryColorLight,
      //     snackPosition: SnackPosition.BOTTOM);
    }
  } catch (error) {
    Log.debug(error);
  } finally {
    EasyLoading.dismiss();
  }
}

Future<void> _share() async {
  EasyLoading.show();
  try {
    await _recorderServiceProvider.shareRecordFileInBook(
        _path, _bookId, _assignmentId);
    if (_recorderServiceProvider.statusMessageResult.value.status == 1000) {
      showSnackMsg('Shared Successfully');
      // Get.snackbar('Message'.tr, 'Shared Successfully'.tr,
      //     backgroundColor: Get.theme.primaryColor,
      //     colorText: Get.theme.primaryColorLight,
      //     snackPosition: SnackPosition.BOTTOM);
    } else {
      showSnackMsg('Error to share');
      // Get.snackbar('Message'.tr, 'Error to share'.tr,
      //     backgroundColor: Get.theme.primaryColor,
      //     colorText: Get.theme.primaryColorLight,
      //     snackPosition: SnackPosition.BOTTOM);
    }
  } catch (error) {
    Log.debug(error);
  } finally {
    EasyLoading.dismiss();
  }
}

// builder timer
Widget _buildTimerText(recordDuration) {
  return _buildTimer(recordDuration);
}

Widget _buildTimer(recordDuration) {
  final String minutes = _formatNumber(recordDuration ~/ 60);
  final String seconds = _formatNumber(recordDuration % 60);
  return ClipOval(
    child: Material(
      child: Container(
        height: 40,
        width: 80,
        alignment: Alignment.center,
        child: Text(
          '$minutes : $seconds',
          style: const TextStyle(
            color: Colors.red,
          ),
        ),
      ),
    ),
  );
}

String _formatNumber(int number) {
  String numberStr = number.toString();
  if (number < 10) {
    numberStr = '0' + numberStr;
  }
  return numberStr;
}

class PlayButton extends StatelessWidget {
  const PlayButton({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<ButtonState>(
      valueListenable: _audiobooksManager.playButtonNotifier,
      builder: (_, value, __) {
        switch (value) {
          case ButtonState.loading:
            return Container(
              margin: EdgeInsets.all(8.0),
              width: 32.0,
              height: 32.0,
              child: CircularProgressIndicator(
                backgroundColor: Get.theme.primaryColorDark,
                strokeWidth: 9.0,
              ),
            );
          case ButtonState.paused:
            return Material(
                color: Colors.transparent,
                child: IconButton(
                  icon: Icon(Icons.play_arrow),
                  iconSize: 32.0,
                  onPressed: _audiobooksManager.play,
                ));
          case ButtonState.playing:
            return Material(
                color: Colors.transparent,
                child: IconButton(
                  icon: Icon(Icons.pause),
                  iconSize: 32.0,
                  onPressed: _audiobooksManager.pause,
                ));
        }
      },
    );
  }
}

class AudioProgressBar extends StatelessWidget {
  const AudioProgressBar({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<ProgressBarState>(
      valueListenable: _audiobooksManager.progressNotifier,
      builder: (_, value, __) {
        return ProgressBar(
          progress: value.current,
          buffered: value.buffered,
          total: value.total,
          onSeek: _audiobooksManager.seek,
        );
      },
    );
  }
}
